package com.zqxx.examine.management.controller.action;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.extr.file.util.FileUploadUtil;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.zqxx.examine.management.security.UserInfo;
import com.zqxx.examine.management.service.QuestionService;
import com.zqxx.examine.model.exam.Message;
import com.zqxx.examine.model.question.KnowledgePoint;
import com.zqxx.examine.model.question.Question;
import com.zqxx.examine.model.question.QuestionTag;

@Controller
public class QuestionAction
{
  @Autowired
  private QuestionService questionService;
  
  @RequestMapping(value={"/secure/question/question-add"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
  @ResponseBody
  public Message addQuestion(@RequestBody Question question)
  {
    UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    Message message = new Message();
    Gson gson = new Gson();
    question.setContent(gson.toJson(question.getQuestionContent()));
    question.setCreate_time(new Date());
    question.setCreator(userDetails.getUsername());
    try
    {
      this.questionService.addQuestion(question);
    }
    catch (Exception e)
    {
      message.setResult("error");
      message.setMessageInfo(e.getClass().getName());
      e.printStackTrace();
    }
    return message;
  }
  
  @RequestMapping(value={"/secure/question/question-tag/{questionId}"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  @ResponseBody
  public Message getQuestionTag(@PathVariable("questionId") int questionId)
  {
    Message message = new Message();
    UserInfo userInfo = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    List<QuestionTag> tagList = this.questionService.getQuestionTagByQuestionIdAndUserId(questionId, userInfo
      .getUserid(), null);
    message.setObject(tagList);
    return message;
  }
  
  @RequestMapping(value={"/secure/question/add-question-tag"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
  @ResponseBody
  public Message addQuestionTag(@RequestBody int questionId, @RequestBody List<QuestionTag> questionTagList)
  {
    Message message = new Message();
    UserInfo userInfo = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    try
    {
      this.questionService.addQuestionTag(questionId, userInfo.getUserid(), questionTagList);
    }
    catch (Exception e)
    {
      e.printStackTrace();
      message.setResult(e.getClass().getName());
    }
    return message;
  }
  
  @RequestMapping(value={"/secure/question/question-detail/{questionId}"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  @ResponseBody
  public Message getQuestionDetail(@PathVariable("questionId") int questionId)
  {
    Message message = new Message();
    try
    {
      Question question = this.questionService.getQuestionDetail(questionId, 0);
      message.setObject(question);
    }
    catch (Exception e)
    {
      e.printStackTrace();
      message.setResult(e.getCause().getMessage());
    }
    return message;
  }
  
  @RequestMapping(value={"/secure/question/question-update/{questionId}/{pointId}"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
  @ResponseBody
  public Message updateQuestionKnowledge(@PathVariable int questionId, @PathVariable int pointId, @RequestBody List<QuestionTag> questionTagList)
  {
    Message message = new Message();
    UserInfo userInfo = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    Question question = new Question();
    question.setId(questionId);
    List<Integer> pointIdList = new ArrayList();
    pointIdList.add(Integer.valueOf(pointId));
    question.setPointList(pointIdList);
    try
    {
      this.questionService.updateQuestionPoint(question, userInfo.getUserid(), questionTagList);
    }
    catch (Exception e)
    {
      message.setResult(e.getClass().getName());
    }
    return message;
  }
  
  @RequestMapping(value={"/secure/question/question-update"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
  @ResponseBody
  public Message updateQuestion(@RequestBody String jsonStr)
  {
    Message msg = new Message();
    Gson gson = new Gson();
    JsonParser parser = new JsonParser();
    JsonElement element = parser.parse(jsonStr);
    List<QuestionTag> questionTagList = (List)gson.fromJson(element.getAsJsonObject().get("tags"), new TypeToken() {}.getType());
    Question question = (Question)gson.fromJson(element.getAsJsonObject().get("question"), Question.class);
    try
    {
      this.questionService.updateQuestion(question, questionTagList);
    }
    catch (Exception e)
    {
      e.printStackTrace();
      msg.setResult(e.getCause().getMessage());
    }
    return msg;
  }
  
  @RequestMapping(value={"/secure/question/get-knowledge-point/{fieldId}"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  @ResponseBody
  public Message getQuestionPointByFieldId(@PathVariable int fieldId)
  {
    Message message = new Message();
    HashMap<Integer, String> pointMap = new HashMap();
    List<KnowledgePoint> pointList = this.questionService.getKnowledgePointByFieldId(fieldId, null);
    for (KnowledgePoint point : pointList) {
      pointMap.put(Integer.valueOf(point.getPointId()), point.getPointName());
    }
    message.setObject(pointMap);
    return message;
  }
  
  @RequestMapping(value={"/secure/question/delete-question/{questionId}"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  @ResponseBody
  public Message deleteQuestion(Model model, @PathVariable("questionId") int questionId)
  {
    Message message = new Message();
    try
    {
      this.questionService.deleteQuestionByQuestionId(questionId);
    }
    catch (Exception ex)
    {
      message.setResult(ex.getClass().getName());
    }
    return message;
  }
  
  @RequestMapping(value={"/secure/upload-uploadify-img"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
  @ResponseBody
  public String uploadImg(HttpServletRequest request, HttpServletResponse response)
  {
    UserInfo userInfo = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    List<String> filePathList = new ArrayList();
    try
    {
      filePathList = FileUploadUtil.uploadImg(request, response, userInfo.getUsername());
    }
    catch (FileNotFoundException e)
    {
      e.printStackTrace();
    }
    catch (Exception ex)
    {
      ex.printStackTrace();
    }
    if (filePathList.size() == 0) {
      return "系统错误";
    }
    return (String)filePathList.get(0);
  }
  
  @RequestMapping(value={"/secure/upload-uploadify"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
  @ResponseBody
  public String uploadFile(HttpServletRequest request, HttpServletResponse response)
  {
    UserInfo userInfo = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    List<String> filePathList = new ArrayList();
    try
    {
      filePathList = FileUploadUtil.uploadQuestionFile(request, response, userInfo.getUsername());
    }
    catch (FileNotFoundException e)
    {
      e.printStackTrace();
    }
    catch (Exception ex)
    {
      ex.printStackTrace();
    }
    if (filePathList.size() == 0) {
      return "系统错误";
    }
    return (String)filePathList.get(0);
  }
  
  @RequestMapping(value={"/secure/question-import/{id}"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
  @ResponseBody
  public Message courseImport(@RequestBody String filePath, @PathVariable("id") int id)
  {
    Message message = new Message();
    
    UserInfo userInfo = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if (id == 0)
    {
      message.setResult("error");
      message.setMessageInfo("请选择题库");
      return message;
    }
    try
    {
      this.questionService.uploadQuestions(filePath, userInfo.getUsername(), id);
    }
    catch (RuntimeException e)
    {
      message.setResult(e.getClass().getName() + ":" + e.getMessage());
      message.setMessageInfo(e.getMessage());
    }
    return message;
  }
}
